{{define "admin/user.html"}}
<!DOCTYPE html>
<html>

<head>
  {{template "layout/head.html" .}}
<style>
  .badge{
    cursor: pointer;
  }
</style>
</head>

<body>
  <div class="wrapper">
    <div class="content-wrapper">
        <div class="container-fluid">
          <div class="row">
            <div class="col-md-12">
                <div class="box">
                    <div class="box-header">
                        <div class="row"  class="margin-left: 0px;">
                            <div class=" form-horizontal searchPanel  form-inline" style="padding-left: 15px;padding-bottom:5px;">
                              
                              <label class=" control-label" style="padding-left:30px; ">显示条数:</label>
                              <div class="btn-group" style="padding-left: 0px;">
                                  <select data-name="pagesize" class="form-control  feild-edit " onclick="User_operat.pageSizeChange(this)">
                                      <option value="10" >10</option>
                                      <option value="20" selected>20</option>
                                      <option value="50">50</option>
                                      <option value="100">100</option>
                                      <option value="1000">1000</option>
                                  </select>
                              </div>                               
                                <label class="control-label" style="padding-left:30px; ">账号:</label>
                                <div class="btn-group" style="padding-left: 0px;">
                                    <input data-name="phone" class="form-control  feild-edit " value="" placeholder="请输入手机号或用户名"/>
                                </div>
                                <div class="btn-group pull-right lay-right" style="margin-left:30px;">
                                    <div class="btn-group " style="width: 60px;margin-right:10px;">
                                        <label class=" btn btn-info" onclick="User_operat.showList()">查询</label>                
                                    </div>
                                    <div class=" btn-group " style="width: 100px;">
                                        <label onclick="User_operat.addUser()"  class=" btn btn-info addPointBtn">+添加用户</label>
                                    </div>
                                </div>
                                
        
                            </div>
                        </div>
                    </div><!-- /.box-header -->
                    <div class="box-body">
                        <div class="dataTables_wrapper form-inline dt-bootstrap" id="example2_wrapper">
                            <div  class="col-md-12 showUserListDiv">
                              <table class="table table-bordered table-hover dataTable userListTable">
                                <thead>
                                  <tr>
                                    <th >序号</th>
                                    <th >员工编号</th>
                                    <th >用户姓名</th>
                                    <th >登录手机号</th>
                                    <th >登录用户名</th>
                                    <th>备注</th>
                                    <th align="center" >操作</th>
                                  </tr>
                                  </thead>
                                  <tbody></tbody>
                                  <tfoot  style="display: none">
                                    <tr>
                                      <td data-type="pUserID"></td>
                                      <td data-type="pUserCD"></td>
                                      <td data-type="pAlias"></td>
                                      <td data-type="pPhone"></td>
                                      <td data-type="pUsername"></td>
                                      <td data-type="pRemarks" ></td>
                                      <td class="__operat" > 
                                        <span class="rolemanage margin badge bg-success" >角色管理</span>|<span class="modify margin badge bg-primary" >修改</span>|<span class="resetpwd margin badge bg-warning">重置密码</span>|<span class="enablestate margin badge bg-danger">禁用</span>
                                      </td>
                                  </tr>
                                  </tfoot>
                                </table>
                            </div>
                            <div class="col-md-12 "><div class="adminuser_myPage pagination pull-right"></div></div>
        
                        </div>
                    </div><!-- /.box-body -->
                </div><!-- /.box -->
            </div>
          </div>
     
    
          <div id="addusermedol" style="display:none">
                  <form class="form-horizontal">
                      <div class="box-body">
      
                          <div class="form-inline row">
                              <label class="col-sm-3 control-label">员工编号：</label>
                              <div class="col-sm-9">
                                <input type="text" class="form-control  modelFeild control-block "
                                                          data-type="pUserCD"        value=""/>
                              </div>
                          </div>
                          <div class="form-inline row"><label class="col-sm-3 control-label">用户姓名：</label>
                              <div class="col-sm-9"><input type="text" class="form-control  modelFeild control-block "
                                                          data-type="pAlias" value=""/></div>
                          </div>
                          
                          <div class="form-inline row loginUserName" style="display: none;"><label class="col-sm-3 control-label">登录用户名：</label>
                            <div class="col-sm-9"><input type="text" class="form-control  modelFeild control-block "
                                                        data-type="pUsername" value=""/></div>
                        </div>
                          <div class="form-inline row"><label class="col-sm-3 control-label">电话号码：</label>
                              <div class="col-sm-9"><input type="text" class="form-control  modelFeild control-block "
                                                          data-type="pPhone" value=""/></div>
                          </div>
                          <div class="form-inline row"><label class="col-sm-3 control-label">性别：</label>
                              <div class="col-sm-9">
                                  <select class="form-control  modelFeild control-block " data-type="pSex">
                                      <option value="0">未知</option>
                                      <option value="1">男</option>
                                      <option value="2">女</option>
                                  </select>
                              </div>
                          </div>
                          <div class="form-inline row"><label class="col-sm-3 control-label">备注：</label>
                              <div class="col-sm-9"><textarea rows="3" class="form-control modelFeild control-block " style="overflow: hidden;"
                                                              data-type="pRemarks" value=""></textarea></div>
                          </div>
                          <div class="form-inline row"><span class="text-red add_error_note"></span></div>
                      </div>
                  </form>
          </div>
      
      
          <div id="user_role_select_contiar_div" style="display: none">
              <div class="box box-success user_role_select_contiar" style="border: none;box-shadow: none;">
                  <div class="box-body" style="border: none;box-shadow: none;">
                  </div>
                  <div class="box-footer" style="border: none;box-shadow: none;">
                      <div class="form-inline row">
                          <span class="text-red"></span>
                      </div>
                  </div>
                  <div class="check_template" style="display: none">
                      <div class="form-inline row">
                          <label class="">
                              <div class="icheckbox_minimal-blue checked" aria-checked="false" aria-disabled="false"
                                  style="position: relative;">
                                  <input type="checkbox" class="minimal" checked=""
                                        style="position: absolute; opacity: 0;"
                                        onclick="$(this).parents('.icheckbox_minimal-blue').hasClass('checked')?$(this).parents('.icheckbox_minimal-blue').removeClass('checked'):$(this).parents('.icheckbox_minimal-blue').addClass('checked')">
                                  <ins class="iCheck-helper"
                                      style="position: absolute; top: 0%; left: 0%; display: block; width: 100%; height: 100%; margin: 0px; padding: 0px; background: rgb(255, 255, 255); border: 0px; opacity: 0;"></ins>
                              </div>
                          </label>
                      </div>
                  </div>
              </div>
          </div>
    
        </div>
    </div>
  </div>


  {{template "layout/foot.html" .}}
  {{template "layout/iframePageFoot.html" .}}
  
  <script src="{{.pageContentPath}}/static/plugins/CryptoJS-v4.0.0/crypto-js.js"></script>
  <script src="{{.pageContentPath}}/static/joyconn/encryptoUtils.js?v=2"></script>

  <link href="{{.pageContentPath}}/static/plugins/ztree_v3/css/metroStyle/metroStyle.css" rel="stylesheet"/>
  <script src="{{.pageContentPath}}/static/plugins/ztree_v3/js/jquery.ztree.all.js"></script>
  <link href="{{.pageContentPath}}/static/plugins/bootstrap-table/bootstrap-table.min.css/" rel="stylesheet"/>
  <script href="{{.pageContentPath}}/static/plugins/bootstrap-table/bootstrap-table.min.js/" ></script>
  <script src="{{.pageContentPath}}/static/plugins/jquery/jquery.pagination.min.js"></script>

  <link href="{{.pageContentPath}}/static/plugins/iCheck/all.css" rel="stylesheet"/>
  <script src="{{.pageContentPath}}/static/plugins/iCheck/icheck.min.js" type="text/javascript"></script>
  <script type="text/javascript">
      /**
      * Created by Eric.Zhang on 2017/1/7.
      */
      var User_operat = function () {

      }
      User_operat.searchParam = {
          searchID: '',
          pageIndex: 1,
          pageSize: 20
      }
      User_operat.pageSizeChange=function(sender){
        var pageSize = $(sender).val();
        User_operat.searchParam.pageSize=pageSize;
        User_operat.showPageList(1);
      }
    //显示用户列表
    User_operat.showList = function () {
        // $(".showUserListDiv").html('<img src="'+static_Resources_Path_Image+'/css/images/loading.gif" />');
        User_operat.searchParam.searchID=$('.searchPanel input[data-name="phone"]').val();
        User_operat.searchParam.pageSize=$('.searchPanel select[data-name="pagesize"]').val();
        User_operat.showPageList(1);

    }
    User_operat.showPageList = function (pageIndex) {
        $('.userListTable tbody').empty()
        $('.adminuser_myPage.pagination').empty()
        JoyDialog.showLoading();
        $.ajax({
            url:page_content_path+ '/api/system/account/user/getUserList',
            data: User_operat.searchParam,
            type: 'get',
            cache: false,
            success: function (txt) {
                JoyDialog.hideLoading();
                if (!joyconn_layout.ValidataResult(txt)) {
                    return;
                }
                if (txt.data&&txt.data.length>0) {
                    $(txt.data).each(function (i,model) {
                        User_operat.ShowListModel(model);
                    });


                    ShowPage($('.adminuser_myPage.pagination').get(0), {
                        pno: pageIndex,
                        pagesize: User_operat.searchParam.pageSize,
                        allcount: txt.allcount
                    }, function (pno) {
                        User_operat.showPageList(pno);
                    });
                } else {
                  $('.userListTable tbody').append('<tr><td colspan="7"><span class="text-red" id="add_error_note">未查询到用户信息</span></td></tr>')
                }
            }
        });

    }
    User_operat.ShowListModel = function (model) {
      var templateEle = $('.userListTable tbody tr[data-id="'+model.pUserID+'"]')
        if (!templateEle||templateEle.length==0) {
            templateEle = $($('.userListTable tfoot').html()).attr('data-id',model.pUserID);
            $('.userListTable tbody').append(templateEle);
        }
        $(templateEle).find("td").each(function (_i, ele) {
            if ($(ele).attr("data-type")) {
                $(ele).html(model[$(ele).attr("data-type")]);
            }
        });
        if(model.IsSuperAdmin){
          $(templateEle).find('.__operat').children().hide();
        }
        $(templateEle).find(".rolemanage").unbind("click").click(function () {
            User_operat.manageUserRole(model)
        });
        $(templateEle).find(".modify").unbind("click").click(function () {
            User_operat.addOrModifyUser(false, model, function (_model) {
                User_operat.ShowListModel(_model);
            });
        });
        $(templateEle).find(".resetpwd").unbind("click").click(function () {
            User_operat.resetUserPwd(model);
        });
        $(templateEle).find(".enablestate").unbind("click").click(function () {
            User_operat.enableUser(templateEle, model);
        }).html((model.pStatus == 1 ? '禁用':'启用'));
    }
    User_operat.manageUserRole=function(userObj){
      var myRoles = null;
      var userRoles = null;
      var getdata1 = $.get(page_content_path+'/api/system/authorize/user/permission/getMyRoles',function(data){
        if (!joyconn_layout.ValidataResult(data)) {
            return;
        }
        myRoles = data.data;
      })
      var getdata2 = $.get(page_content_path+'/api/system/authorize/user/permission/getUserRoles?fUserid='+userObj.pUserID,function(data){
        if (!joyconn_layout.ValidataResult(data)) {
            return;
        }
        userRoles = data.data;
      })      
      JoyDialog.showLoading();
      $.when(getdata1,getdata2).then(function(){
        
        JoyDialog.hideLoading();
        var myRoleIDs = []
        var userRoleIDs = [];
        var appids = [];
        var allRoleIds=[]
        var allRoleObjs=[]
        if(userRoles){
          $(userRoles).each(function(i,obj){
              userRoleIDs.push(obj.pId)
              appids.push(obj.pAppid)              
              if($.inArray(obj.pId,allRoleIds)<0){
                allRoleIds.push(obj.pId)
                allRoleObjs.push(obj)
              }
          })
        }
        
        if(myRoles){
          $(myRoles).each(function(i,obj){
              myRoleIDs.push(obj.pId)
              appids.push(obj.pAppid)
              if($.inArray(obj.pId,allRoleIds)<0){
                allRoleIds.push(obj.pId)
                allRoleObjs.push(obj)
              }
          })
        }        
        allRoleObjs.sort(function(a1,a2){
          return a1.pId-a2.pId
        })
        var RoleDiv;
        showRoleDiv()
        function showRoleDiv(){
          var div = $('<div class="box box-success user_role_select_contiar" style="border: none;box-shadow: none;overflow-y: auto; max-width: 38em;min-width: 300px;">\n' +
                '            <div class="box-body" style="border: none;box-shadow: none;">\n' +
                '            </div>\n' +
                '            <div class="box-footer" style="border: none;box-shadow: none;">\n' +
                '                <div class="form-group">\n' +
                '                    <span class="text-red"></span>\n' +
                '                </div>\n' +
                '            </div>\n' +
                '        </div>');
            RoleDiv = div;
            var height = $(window).height();
            height = height - 180;
            var width = $(window).width();
            width = width - 100;
            $(div).css('width',width+'px').height(height);
            $(allRoleObjs).each(function (i, a) {
                var _element = $('<div class="form-group"> ' +
                    '<label class=""  title="' + a.pName + '">'+
                    '<input type="checkbox" data-id="' + a.pId + '" data-appid="' + a.pAppid + '" value="' + a.pId + '" />' +
                    '<span style="padding: 0 5px;" data-appid="'+a.pAppid+'"></span>'+
                    '<span>' + a.pName + '</span>' +
                    '</label>' +
                    '</div>');
                $(div).find(".box-body").append(_element);
                _element.iCheck({
                    checkboxClass: 'icheckbox_square-blue',
                    radioClass: 'iradio_square-blue',
                    increaseArea: '20%' // optional
                });
                if($.inArray(a.pId,userRoleIDs)>-1){
                  _element.iCheck('check')
                }
                if($.inArray(a.pId,myRoleIDs)<0){
                  _element.iCheck('disable')
                }
            });
            var dia = JoyDialog({
                titleText: '修改用户角色',
                content: div.get(0),
                // width: '400px',
                buttonTextCancel:"取消",
                buttonTextConfirm: '修改',
                onClickConfirmBtn: doPostUserRole
            });
            getAppName()
        }
        function getAppName(){
          $.post(page_content_path+'/api/system/authorize/app/getApps',{appids:$.unique(appids.sort())},function(data){
            if (!joyconn_layout.ValidataResult(data)) {
                return;
            }
            if(!data.data){
              return
            }
            $(data.data).each(function(i,obj){
              RoleDiv.find('span[data-appid="'+obj.pId+'"]').html(obj.pName).attr('title',obj.pDesc)
            })
          })
        }
        function doPostUserRole(){
            var roleObjs=[]
            RoleDiv.find('input:checkbox:checked').each(function(i,input){
              roleObjs.push({limit:'2050-12-12 23:23:59',role:$(input).attr("data-id")*1})
            })
            $.post(page_content_path+'/api/system/authorize/user/permission/update',JSON.stringify({pUserID:userObj.pUserID,pRoleObjs:roleObjs}),function(data){
            if (!joyconn_layout.ValidataResult(data)) {
                return;
            }
            if (data.data > 0) {
                  JoyDialog({
                      type:'toast_success',
                      titleText: '成功',
                      infoText:  '修改成功',
                      buttonTextCancel:false
                  });
                  dia.close()
              }
              else {
                JoyDialog({
                    titleText: '错误',
                    content:  '修改失败',
                    buttonTextCancel:false
                });
              }
            
          })
          return false;
        }
      })

    }

    //启用、禁用用户
    User_operat.enableUser = function (templateEle, model) {
        var stat = (model.pStatus == 0 ? 1 : 0);
        var showStr = (model.pStatus == 1 ? '禁用' :'启用'  );
        var dia = JoyDialog({
              titleText: showStr+'用户',
              content: '要'+showStr+'用户"'+(model.pAlias)+'('+model.pUserID+')"吗?',
              // width: '400px',
              buttonTextCancel:"取消",
              buttonTextConfirm: showStr,
              onClickConfirmBtn: doPost
          });
          function doPost(){
            
            JoyDialog.showLoading();
            $.ajax({
                url: page_content_path+'/api/system/account/user/changeUserStat',
                data: {uid: model.pUserID, stat: stat},
                type: 'post',
                cache: false,
                success: function (data) {
                    JoyDialog.hideLoading();
                    if (!joyconn_layout.ValidataResult(data)) {
                        return;
                    }
                    if (data.data > 0) {
                        JoyDialog({
                            type:'toast_success',
                            titleText: '成功',
                            infoText:  showStr + '用户成功',
                            buttonTextCancel:false
                        });
                        dia.close()
                        model.pStatus = stat;
                        User_operat.ShowListModel(model);
                    }
                    else {
                      JoyDialog({
                          titleText: '错误',
                          content: showStr + '用户失败',
                          buttonTextCancel:false
                      });
                    }
                }
            });
          }
        
    }
    //添加用户
    User_operat.addUser = function () {
        User_operat.addOrModifyUser(true, null, function (_model) {
            User_operat.ShowListModel(_model);
        });
    }
    //修改用户
    User_operat.addOrModifyUser = function (isAdd, model, callback) {

        var diaElement = $($("#addusermedol").html());
        if (model) {
            $(diaElement).find(".modelFeild").each(function (i, ele) {
                if ($(ele).attr("data-type") != "smsenable") {
                    $(ele).val(model[$(ele).attr("data-type")]);
                }
            });
        } else {
            model = {pStatus: 1, pHeadPortrait: '/static/plugins/adminlte/img/user8-128x128.jpg'};
            diaElement.find('.loginUserName').show()
        }
        var title = (isAdd ? "添加" : "修改");
        var dia = JoyDialog({
            titleText:title + '用户',
            content: diaElement.get(0),
            // width: '400px',
            buttonTextCancel:"取消",
            buttonTextConfirm: title,
            onClickConfirmBtn: ClickConfirmBtn
        });
        function ClickConfirmBtn(){
            var errorNote = $(diaElement).find(".add_error_note");
            errorNote.html("");
            var postModel = JSON.parse(JSON.stringify(model))
            $(diaElement).find(".modelFeild").each(function (i, ele) {
                if ($(ele).attr("data-type") == "pPhone") {
                  if($(ele).val()){
                    var reg = /^1(3|4|5|7|8|9)\d{9}$/;
                    if (!reg.test($(ele).val())) {
                        errorNote.html("手机号填写错误");
                        return false;
                    }
                  }
                }
                if ($(ele).attr("data-type") == "pSex") {
                  if($(ele).val()){
                    postModel[$(ele).attr("data-type")] = $(ele).val()*1
                  }
                }else{
                  postModel[$(ele).attr("data-type")] = $(ele).val()
                }
            })
            if (errorNote.html() != '') {
                return false;
            }
            var url = isAdd ? "/api/system/account/user/addUser" : "/api/system/account/user/modifyUserModel";
            
            JoyDialog.showLoading();
            $.ajax({
                url: page_content_path+url,
                data:JSON.stringify( postModel) ,
                type: 'post',
                cache: false,
                success: function (txt) {
                    JoyDialog.hideLoading();
                    if (!joyconn_layout.ValidataResult(txt)) {
                        return;
                    }
                    if (isAdd) {
                        if (txt.data) {                                
                            JoyDialog({
                                titleText: '成功',
                                content: title + '用户成功',
                                buttonTextCancel:false
                            });
                            dia.close()
                            if (callback) {
                                callback(txt.data);
                            }
                        } else {
                            JoyDialog({
                                titleText: '错误',
                                content: '修改用户失败,请检测用户信息是否准确,手机号是否已被占用',
                                buttonTextCancel:false
                            })
                        }
                    } else {
                        if (txt.data > 0) {
                          
                            JoyDialog({
                                titleText: '成功',
                                content: title + '用户成功',
                                buttonTextCancel:false
                            });
                            dia.close()
                            if (callback) {
                                callback(postModel);
                            }
                        }
                        else {
                            JoyDialog({
                                titleText: '错误',
                                content: title + '用户失败',
                                buttonTextCancel:false
                            });
                        }
                    }

                }
            });
            return  false;
          }
    

        $(diaElement).find('input[type="checkbox"]').iCheck({
            checkboxClass: 'icheckbox_square-green'  //class类名，控制选框样式
        });
        if (model.smsenable == "True") {
            $(diaElement).find('input[type="checkbox"]').iCheck('check');
        }

    }


    //重置密码
    User_operat.resetUserPwd = function (model) {
        var pwd = '123456';
        var dia = JoyDialog({
              titleText: '重置用户密码',
              content: '要重置用户"'+(model.pAlias)+'('+model.pUserID+')"的密码吗?',
              // width: '400px',
              buttonTextCancel:"取消",
              buttonTextConfirm: '重置',
              onClickConfirmBtn: doPost
          });
          function doPost(){
            JoyDialog.showLoading();
            $.ajax({
                url: page_content_path+'/api/system/account/user/resetPwd',
                data: {uid: model.pUserID, pwd:encryptoPwd(pwd,'{{.ParamEncryptKey}}')  },
                type: 'post',
                cache: false,
                success: function (txt) {
                    JoyDialog.hideLoading();
                    if (!joyconn_layout.ValidataResult(txt)) {
                        return;
                    }
                    if (txt.data > 0) {
                      JoyDialog({
                          titleText: '成功',
                          content: '密码已重置为：' + pwd + '，请牢记！',
                          buttonTextCancel:false
                      });
                      dia.close()
                    }
                    else {
                      JoyDialog({
                          titleText: '错误',
                          content: '重置密码失败',
                          buttonTextCancel:false
                      });
                    }
                }
            });
          }
        
    }



    $(function () {
        User_operat.showList();
    });
  </script>
</body>

</html>
{{end}}